import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:image_picker/image_picker.dart';
class TuiKuanPage extends StatefulWidget {
  final String odid;//订单详情id
  final String orid;//订单id
  final String gid;//商品id
  TuiKuanPage({Key key, this.title, this.odid, this.orid, this.gid}) : super(key: key);

  final String title;

  @override
  _TuiKuanPage createState() => _TuiKuanPage(odid,orid,gid);
}

class _TuiKuanPage extends State<TuiKuanPage> {
  final String odid;
  final String orid;
  final String gid;
  var dropdownValue;  // 退款原因的下标
  dynamic _imgPath;   // 第一个图片的显示地址
  dynamic _imgPath2;   // 第二个图片的显示地址
  dynamic _imgPath3;   // 第三个图片的显示地址
  var tu1;            // 服务器返回的第一个图片的地址
  var tu2;
  var tu3;

  _TuiKuanPage(this.odid, this.orid, this.gid);

  TextEditingController _refundDiscription = new TextEditingController();
  TextEditingController _phone = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 464, height: 820);
    // 上传的图片

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("申请退款"),
      ),
      body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(child: Text("申请原因"),),
              Container(
                  child: DropdownButton<String>(
                    value: dropdownValue,
                    icon: Icon(Icons.arrow_forward_ios),
                    iconEnabledColor: Colors.blue,
                    dropdownColor: Colors.white,
                    underline: SizedBox(height:10,),
                      hint:Text("选择退款原因") ,
                    onChanged: (String newValue) async {
                      setState(() {
                        dropdownValue = newValue;
                      });
                    },
                    items: <String>[
                      '商家没发货',
                      '我不喜欢了',
                      '拍错了',
                      '其他原因',
                    ].map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child:Text(value),
                      );
                    }).toList(),
                  )
              )
            ],
          ),
          Container(
            child: Column(
              children: [
                Row(children: [Text("申请说明")],),
                TextField(
                  controller: _refundDiscription,
                  onChanged: (value){
                    _refundDiscription.text=value;
                    final length=value.length;
                    _refundDiscription.selection = TextSelection(baseOffset: length, extentOffset: length);
                  },
                ),
              ],
            ),
          ),
          Container(
            child: Row(
              children: [
                Text("联系方式"),
                Expanded(child:
                TextField(
                  controller: _phone,
                  onChanged: (value){
                    _phone.text=value;
                    final length=value.length;
                    _phone.selection = TextSelection(baseOffset: length, extentOffset: length);
                  },
                ),
                )
              ],
            )
          ),
          Container(
            child: Column(
              children: [
                Row(children: [
                  Container(
                    child:  Text("照片凭证（可选，最多三张）"),
                    margin: EdgeInsets.symmetric(vertical: 10),
                  )

                ],
                ),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                   tu1==null?Text(""): _ImageView(_imgPath,tu1),
                   tu1!=null?Text(""): GestureDetector(
                      child: Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black , width: 0) ,
                        ),
                        child: Center(child: Text("+"),),
                      ),
                      onTap: () async {
                        print(0000);
                        final ImagePicker _picker = ImagePicker();
                        var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                        // XFile image = await _picker.pickImage(source: ImageSource.gallery);
                        _imgPath=s;
                        // print(s.path);   // 获取文件路径
                        File file = new File(s.path);
                        var res = await HttpUtil().upload("/upload", file);
                        print(res);
                        tu1 = res['data'];
                        setState(()  {

                        });
                      },
                    ),
                    tu2==null?Text(""): _ImageView(_imgPath2,tu2),
                    tu2!=null?Text(""): GestureDetector(
                      child: Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black , width: 0) ,
                        ),
                        child: Center(child: Text("+"),),
                      ),
                      onTap: () async {
                        final ImagePicker _picker = ImagePicker();
                        var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                        // XFile image = await _picker.pickImage(source: ImageSource.gallery);
                        _imgPath2=s;
                        // print(s.path);   // 获取文件路径
                        File file = new File(s.path);
                        var res = await HttpUtil().upload("/upload", file);
                        print(res);
                        tu2 = res['data'];
                        setState(()  {

                        });
                      },
                    ),
                    tu3==null?Text(""): _ImageView(_imgPath3,tu3),
                    tu3!=null?Text(""): GestureDetector(
                      child: Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black , width: 0) ,
                        ),
                        child: Center(child: Text("+"),),
                      ),
                      onTap: () async {
                        print(0000);
                        final ImagePicker _picker = ImagePicker();
                        var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                        // XFile image = await _picker.pickImage(source: ImageSource.gallery);
                        _imgPath3=s;
                        // print(s.path);   // 获取文件路径
                        File file = new File(s.path);
                        var res = await HttpUtil().upload("/upload", file);
                        print(res);
                        tu3 = res['data'];
                        setState(()  {

                        });
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
          Container(
            child: GestureDetector(
              child:  Container(
                  margin: EdgeInsets.only(top: 20),
                  width:80,
                  // padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                  child: Center(child:Text("提交",style: TextStyle(color: Colors.white),)),
                  decoration: BoxDecoration(
                    color: Colors.deepOrange,
                    borderRadius: BorderRadius.all(Radius.circular(20.0)),
                  )
              ),
              onTap: () async {
                print("提交申请");
                int refund_reason=getRefund_reason(dropdownValue);
                SharedPreferences prefs = await SharedPreferences.getInstance();
                String userId = prefs.getString("userId");
                if(refund_reason==null) {
                  Fluttertoast.showToast(
                      msg: "请选择退款原因",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.black45,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                  return ;
                }
                if(_refundDiscription.text.trim()==null || _refundDiscription.text.trim()=='') {
                  Fluttertoast.showToast(
                      msg: "请填写退款说明",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.black45,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                  return ;
                }
                if(_phone.text.trim()==null || _phone.text.trim()=='' ) {
                  Fluttertoast.showToast(
                      msg: "请填写联系方式",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.black45,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                  return ;
                }
                var map=new Map<String,dynamic>();
                map['orId']=orid;
                map['odId']=odid;
                map['gid']=gid;
                map['user_contact']=_phone.text.trim();
                map['refund_type']='0';
                map['refund_reason']=refund_reason;
                map['refund_describe']=_refundDiscription.text.trim();
                map['userId']=userId;
                map['picture1']=tu1;
                map['picture2']=tu2;
                map['picture3']=tu3;
                print(orid);
                var x = await HttpUtil().post("app/refunds/userTuikuan", map);
                var result = json.decode(x.toString());
                if(result["code"]==200){
                  Fluttertoast.showToast(
                      msg: result['msg'],
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 2,
                      backgroundColor: Colors.black45,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                  MyRoute.pop(1);
                }else{
                  Fluttertoast.showToast(
                      msg: result['msg'],
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.black45,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                }
              },
            ),
          )
        ],
      ),
    );
  }
  //根据退货原因获得对应的代表数字
  int getRefund_reason(value){
    if(value=='商家没发货'){
      return 6;
    }else if(value=='我不喜欢了'){
      return 4;
    }else if(value=='拍错了'){
      return 5;
    }else if(value=='其他原因'){
      return 0;
    }
  }
  /*图片控件*/
  Widget _ImageView(imgPath,tu) {
    if (imgPath == null) {
      return Center(
        child: Text("请选择图片或拍照"),
      );
    } else {
      return Image.network(Config.getInstance().getHost()+'tmp/'+tu,width: 90,height: 100,);
    }
  }
}